import {apiHost} from '../src/config'
// 引入mockjs
const Mock = require('mockjs')
const files = require.context('./api', true, /\.js$/)

const whites = []
const responses = {};
files.keys().forEach(key => {
  const apis = files(key) || {};
  for (const api in apis) {
    let res = apis[api]
    if (typeof apis[api] === 'function') {
      res = whites.includes(api) && apis[api]()
    }
    // 将所有API mock加进去
    if (res && res.url) {
      responses[res.url + res.method] = {
        url: res.url,
        data: res.data,
        method: res.method
      }
    }
  }
  delete responses[undefined]
  delete responses[NaN]
})
for (const key in responses) {
  // 正则解决带参get请求
  Mock.mock(new RegExp('/mock' + apiHost.slice(0,-1) + responses[key].url + ".*"), responses[key].method, (req, res) => { // 当post或get请求到/api/data路由时Mock会拦截请求并返回上面的数据
		return responses[key].data
  })
}
